package com.hjy.attendance.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjy.attendance.dao.AttendanceSonDao;
import com.hjy.attendance.dao.LeaveDao;
import com.hjy.attendance.entity.*;
import com.hjy.attendance.enums.AttendSFEnum;
import com.hjy.attendance.enums.AttentanceEnum;
import com.hjy.attendance.enums.ResultEnum;
import com.hjy.attendance.enums.ValidEnum;
import com.hjy.attendance.exception.ApiException;
import com.hjy.attendance.service.*;
import com.hjy.attendance.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>标题:  Service 实现类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2020</p>
 *
 * @version: 1.0
 * @author: huangjunyu
 * @date 2020-04-18
 */
@Service
public class LeaveServiceImpl extends BaseServiceImpl<LeaveDao, Leave> implements LeaveService {

    @Autowired
    private AttendanceSonDao attendanceSonDao;

    @Autowired
    private LeaveDao leaveDao;

    @Autowired
    private AttendanceSonService attendanceSonService;

    @Autowired
    private AttendanceParentService attendanceParentService;

    @Autowired
    UserService userService;

    @Autowired
    TeacherService teacherService;

    @Override
    public List<Map<String,Object>> getByCondition(Map<String, Object> map) throws ApiException {
        List<LeaveVo> byCondition = this.baseDao.getByCondition(map);
        return byCondition.stream().map(o ->{
            if(o.getValidFlag().equals(ValidEnum.UNPROCESSED.type)){
                o.setLeaveResult(ValidEnum.UNPROCESSED.value);
            }else if(o.getValidFlag().equals(ValidEnum.AGREE.type)){
                o.setLeaveResult(ValidEnum.AGREE.value);
            }else if(o.getValidFlag().equals(ValidEnum.DISAGREE.type)){
                o.setLeaveResult(ValidEnum.DISAGREE.value);
            }else{
                o.setLeaveResult(ValidEnum.UNPROCESSED.value);
            }
            return o;
        }).map(BeanUtil::transBean2Map)
                .peek(data->{
                    try {
                        data.put("leaveReason",new String((byte[])data.get("leaveReason"),"UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void agree(Leave leaves) throws Exception {
        String studentNo = leaves.getStudentNo();
        Long startTime = leaves.getLeaveStartTime().getTime();
        Long endTime = leaves.getLeaveEndTime().getTime();
        List<AttendanceSon> attendanceSon = attendanceSonDao.agreeAttendanceSon(studentNo);
        attendanceSon.stream().map(data->{
            AttendanceParent parent=(attendanceParentService.getOne(new QueryWrapper<>(AttendanceParent.builder().guid(data.getAttentanceParentId()).build())));
            Map<String,Object> res= BeanUtil.transBean2Map(data);
            res.put("allow_difference_time",parent.getAllowTimeDifference());
            return res;
        }).forEach(data->{
            long allowDifferenceTime=((Date)data.get("allow_difference_time")).getTime();
            AttendanceSon son=AttendanceSon.builder().guid(data.get("guid").toString()).build();
            if (startTime<=allowDifferenceTime && allowDifferenceTime<=endTime){
                son.setSuccessFlag(1);
                son.setAttentanceRecordStartTime(new Date());
                son.setAttentanceFlag(3);
                attendanceSonService.updateById(son);
            }

        });
        Leave leave=Leave.builder().guid(leaves.getGuid()).validFlag(1).judgeTime(new Date()).build();
        updateById(leave);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disagree(Leave leaves) throws ApiException {
        Leave l=Leave.builder().guid(leaves.getGuid()).validFlag(2).judgeTime(new Date()).build();
        updateById(l);
    }

    @Override
    public void publish(Map<String,Object> param) throws Exception{
        JSONObject leave= (JSONObject) param;
        leave.put("leaveReason",leave.get("leaveReason").toString().getBytes("UTF-8"));
        leave.put("leaveImageContent",leave.get("leaveImageContent").toString().getBytes("UTF-8"));
        Leave l= JSON.parseObject(leave.toJSONString(),Leave.class);
        l.setCreateTime(new Date());
        //首先判断是否有正在处理的假条
        Optional unCheck=Optional.ofNullable(getOne(new QueryWrapper<>(Leave.builder().studentNo(l.getStudentNo()).validFlag(0).build())));
        if (unCheck.isPresent()){
            throw  new ApiException(ResultEnum.CUSTOMFAILURE,"你当前有一条请假还未处理,不得重复申请");
        }
        l.setGuid(UUID.randomUUID().toString());
        insert(l);
    }

    @Override
    public List<Map<String, Object>> getAllLeaves(String studengNo) throws Exception {
        List<Leave> leaves=list(new QueryWrapper<>(Leave.builder().studentNo(studengNo).build()));
        return leaves.stream().map(data->{
            Map<String,Object> res=BeanUtil.transBean2Map(data);
            String judgeId=data.getJudgeId();
            if (judgeId.equals("admin")){
                res.put("judgeName","管理员");
            }else{
                res.put("judgeName",teacherService.getById(judgeId).getName());
            }
            res.put("leaveResult",data.getValidFlag()==0?"未处理":(data.getValidFlag()==1?"通过":"驳回"));
            try {
                res.put("leaveReason",new String(data.getLeaveReason(),"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return res;
        }).collect(Collectors.toList());

    }

}
